//
//  SCAWishController.m
//  Mutal
//
//  Created by TonyStart on 16/10/22.
//  Copyright © 2016年 com.wx. All rights reserved.
//

#import "SCAWishController.h"
//#import <AVFoundation/AVFoundation.h>
#import "SCAlertView.h"
#import "SCAWishSaveController.h"
#import "SCHeaderView.h"
#import "SCLoginController.h"
@interface SCAWishController ()<UITextViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property(nonatomic,strong)UITextView *wishContentView;
@property(nonatomic,strong)UIImagePickerController *imagePickerController;
@property(nonatomic,strong)UITextField *titleField;
@property(nonatomic,strong)NSMutableArray *photosArray;
@end
#define SCREEN_SIZE [UIScreen mainScreen].bounds.size
#define DEFAULT_PLACEHOLDER @"描述详情,比如:简单的介绍自己...为什么要发布..."
@implementation SCAWishController

-(UIImagePickerController *)imagePickerController{
    if (!_imagePickerController) {
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.delegate = self;
    }
    return _imagePickerController;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}
-(NSMutableArray *)photosArray{
    if (!_photosArray) {
        _photosArray = [NSMutableArray array];
    }
    return _photosArray;
}
-(void)setupUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupNavgationItem];
    [self setupContent];
    
}

-(void)setupNavgationItem{
    SCHeaderView *headerView = [[SCHeaderView alloc] init];
    [headerView.leftBtn setTitle:@"发布愿望" forState:UIControlStateNormal];
    [headerView.leftBtn setImage:[UIImage imageNamed:@"left"] forState:UIControlStateNormal];
    [headerView.leftBtn addTarget:self action:@selector(backPre) forControlEvents:UIControlEventTouchUpInside];
    
    [headerView.rightBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [headerView.rightBtn addTarget:self action:@selector(nextStep) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:headerView];
}
-(void)setupContent{
    _titleField = [[UITextField alloc] initWithFrame:CGRectMake(0, 64, SCREEN_SIZE.width, 30)];
    
    _titleField.borderStyle = UITextBorderStyleNone;
    _titleField.placeholder = @"标题(用一句话描述你的愿望目的)";
    
    UIView *speatorView = [[UIView alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(_titleField.frame), SCREEN_SIZE.width -20, 1)];
    speatorView.backgroundColor = [UIColor grayColor];

    
    _wishContentView = [[UITextView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_titleField.frame)+5, SCREEN_SIZE.width, 150)];
    _wishContentView.textColor = [UIColor grayColor];
    _wishContentView.text = DEFAULT_PLACEHOLDER;
    _wishContentView.font = [UIFont systemFontOfSize:14];
    _wishContentView.delegate = self;
    
    UIView *speatorView2 = [[UIView alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(_wishContentView.frame), SCREEN_SIZE.width -20, 1)];
    speatorView2.backgroundColor = [UIColor grayColor];
    
    UIButton *cameraBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_SIZE.width - 40 - 20, CGRectGetMaxY(_wishContentView.frame)+10, 40, 40)];
    
    [cameraBtn setImage:[UIImage imageNamed:@"添加照片"] forState:UIControlStateNormal];
    [cameraBtn addTarget:self action:@selector(openCamera) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_titleField];
    [self.view addSubview:speatorView];
    [self.view addSubview:_wishContentView];
    [self.view addSubview:speatorView2];
    [self.view addSubview:cameraBtn];
    
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:DEFAULT_PLACEHOLDER]) {
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
    }
    return YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    [self.view endEditing:YES];
}
-(BOOL)textViewShouldEndEditing:(UITextView *)textView{
    if ([textView.text  isEqual: @""]) {
        textView.textColor = [UIColor grayColor];
        textView.text = DEFAULT_PLACEHOLDER;
    }
    return YES;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
-(void)openCamera{
    UIAlertController *alertVC  = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self LocalPhoto];
    }];
    
    [alertVC addAction:cancelAction];
    [alertVC addAction:cameraAction];
    [alertVC addAction:albumAction];
    
    [self presentViewController:alertVC animated:YES completion:^{
        
    }];
}

//从相册选择
-(void)LocalPhoto{
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {

        //资源类型为图片库
        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        //设置选择后的图片可被编辑
        self.imagePickerController.allowsEditing = YES;
        [self presentViewController:self.imagePickerController animated:YES completion:^{
            
        }];
    }
    
    
    
}
//拍照
-(void)takePhoto{
    //判断是否有相机
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        //设置拍照后的图片可被编辑
        self.imagePickerController.allowsEditing = YES;
        //资源类型为照相机
        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;

        [self presentViewController:self.imagePickerController animated:YES completion:^{
            
        }];
    }else {
        NSLog(@"该设备无摄像头");
    }
}
//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //如果选中了超过3张图片 提示不能再选择了
    if (self.photosArray.count>=3) {
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:^{
            
        }];
        [SCAlertView alertViewWithTitle:@"只能选择3张相片.."];
        return;
    }
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    for (UIView *view in self.view.subviews) {
        if ([view isKindOfClass:[UIImageView class]]) {
            [view removeFromSuperview];
        }
    }
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
//        NSData *data;
//        if (UIImagePNGRepresentation(image) == nil)
//        {
//            data = UIImageJPEGRepresentation(image, 1.0);
//        }
//        else
//        {
//            data = UIImagePNGRepresentation(image);
//        }
        [self.photosArray addObject:image];
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
//        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
//        NSFileManager *fileManager = [NSFileManager defaultManager];
//        
//        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
//        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
//        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:^{
            
        }];
        CGFloat imgWidth = 40;
        CGFloat margin = 10;
        //创建一个选择后图片的小图标放在下方
        //类似微薄选择图后的效果
        for (int i=0; i<self.photosArray.count; i++) {
            UIImageView *smallimage = [[UIImageView alloc] initWithFrame:CGRectMake(margin+(margin+imgWidth)*i, CGRectGetMaxY(self.wishContentView.frame)+10, imgWidth, imgWidth)];
            
            smallimage.image = self.photosArray[i];
            //加在视图中
            [self.view addSubview:smallimage];
        }
        
        
    } 
    
}
-(void)backPre{
    [self dismissViewControllerAnimated:NO completion:^{
        
    }];
}

-(void)nextStep{
    if ([_titleField.text isEqualToString:@""]) {
        [SCAlertView alertViewWithTitle:@"愿望标题不能为空"];
        return;
    }
    if ([_wishContentView.text isEqualToString:@""]) {
        [SCAlertView alertViewWithTitle:@"愿望内容不能为空"];
        return;
    }
    
    SCAWishSaveController *wishSaveVC = [[SCAWishSaveController alloc] init];
    SCAWishModel *awishModel = [[SCAWishModel alloc] init];
    
    awishModel.wish_title = _titleField.text;
    awishModel.wish_desc = _wishContentView.text;
    awishModel.pics = self.photosArray;
    wishSaveVC.wish = awishModel;
    
    [self presentViewController:wishSaveVC animated:NO completion:^{
        
    }];
}


@end
